<?php
namespace app\api\controller;

use addons\epay\library\Service;
use app\api\service\UsersService;
use app\common\controller\Api;
use app\common\model\ConfigForum;
use app\common\model\Circle;
use app\common\model\circle\Admin as CircleAdmin;
use app\common\model\circle\User as CircleUser;
use app\common\model\circle\Level as CircleLevel;
use app\common\model\circle\Notice;
use app\common\model\circle\Noticelog;
use app\common\model\circle\Rult;
use app\common\model\publics\Banner;
use app\common\model\publics\Follow;
use app\common\model\publics\Huati;
use app\common\model\publics\Indexcate;
use app\common\model\publics\Soulog;
use app\common\model\publics\Exp as PublicsExp;
use app\common\model\shop\Goods;
use app\common\model\Trends;
use app\common\model\trends\Banner as Banner2;
use app\common\model\trends\Cate2;
use app\common\model\trends\Comment;
use app\common\model\Scenic;
use app\common\model\CustomerService;
use fast\Http;
use SimpleImage;
use think\Config;
use think\Db;

/**
 * 首页接口
 */
class Index extends Api
{
	protected $connection = 'database.db_second';//连接配置
	protected $noNeedLogin = ['*'];
	protected $noNeedRight = ['*'];

	/**
	 * 首页
     * 
	 * @ApiMethod (POST)
	 * @param int $circle_id 圈子id
	 */
	public function index()
	{
		$user_id   = $this->auth->id;
		$circle_id = $this->request->post('circle_id', '');

		if (!$circle_id) {
			$circle_id = Config::get("site2.ggqz");
		}
		$circle = Circle::get($circle_id);

        if (!$circle) {
			$this->success('圈子不存在', [], 2);
		}
		$site               = Config::get("site2");
		$data               = [];
		$data['circle_id']  = $circle_id;
		$data['name']       = $circle->name;
		$data['logo_image'] = cdnurl($circle->logo_image, true);
		$data['image_url']  = $circle->image ? cdnurl($circle->image, true) : cdnurl($site['circle_img'], true);
		$data['dt_show_open'] =  Config::get("site2.dt_show_open");

		if ($circle_id == 1) {//平台的
			//$data['trends_count'] = Db::connect($this->connection)->name('trends')->count();
			$data['trends_count'] = count(Trends::select());
			$data['user_count']   = Db::name('user')->count();
		} else {
			$data['trends_count'] = Trends::where(['circle_id' => $circle_id, 'deletetime' => NULL])->count(); //过滤删除的动态
			$data['user_count']   = CircleUser::where(['circle_id' => $circle_id])->count();
		}

		//分类
		//$data['header_cate'] = Indexcate::where(['circle_id' => $circle_id])->order("weigh asc")->select();
        $data['header_cate'] = Indexcate::get_index_cate_recommend($user_id, $circle_id);

		//轮播
		$data['banner'] = Banner::where(['circle_id' => $circle_id, 'status' => 2])->order("is_platform asc,weigh asc")->select();
		
        $contents = $circle->notice;
		if(!$contents) $contents = $site['fabu'];
		//公告
		$notice = Notice::where(['circle_id' => $circle_id, 'status' => 2, 'is_show' => 1])->find();
		if ($notice) {
			//是否查看过最新公告
			$noticelog = Noticelog::where(['user_id' => $user_id, 'circle_id' => $circle_id, 'noticle_id' => $notice->id])->find();
			if ($noticelog) {
				$is_tan = 1;//是
			} else {
				$is_tan = 2;//否
			}

			$data['tan'] = ['notice_id' => $notice->id, 'content' => $notice->content, 'contents' => $contents, 'is_tan' => $is_tan];
		} else {
			//是否查看过最新公告
			$noticelog = Noticelog::where(['user_id' => $user_id, 'circle_id' => $circle_id, 'noticle_id' => 1])->find();
			if ($noticelog) {
				$is_tan = 1;//是
			} else {
				$is_tan = 2;//否
			}
			$data['tan'] = ['notice_id' => 1, 'content' => $site['tan'], 'contents' => $contents, 'is_tan' => $is_tan];
		}

		//校园热榜
		$hot_list = Trends::where(['circle_id' => $circle_id, 'state' => 1])->order('vc_sum desc')->limit(5)->select();
		foreach ($hot_list as $row) {
			$row->visible(['id', 'title']);
		}
		$data['hot_list'] = $hot_list;
		//动态分类
		$data['trends_cate'] = Cate2::where(['circle_id' => $circle_id, 'is_show' => 1])->select();

		if ($circle->join_state == 1 && $user_id) {
			$this->join_circle($circle_id, $user_id);
		}
		$data['join_state'] = $circle->join_state;
		//判断圈友身份
		$circle_user = CircleUser::where(['user_id' => $user_id, 'circle_id' => $circle_id])->find();
		if ($circle_user) {
			$data['identity'] = $circle_user->identity;
			$data['is_auth']  = $circle_user->is_auth;
			$data['is_ban']   = $circle_user->is_ban;
		} else {

			if ($user_id == $circle->user_id) {
				$data['identity'] = 1;
			} else {
				$data['identity'] = 0;
			}

			$data['is_auth'] = 1;
			$data['is_ban']  = 2;
		}

		//查询今天是否访问过圈子
		$accesslog = Db::connect($this->connection)->name('circle_accesslog')->where(['circle_id' => $circle_id, 'user_id' => $user_id, 'day' => date("Y-m-d")])->find();
		if (!$accesslog && $user_id) {
			Db::connect($this->connection)->name('circle_accesslog')->insert(['circle_id' => $circle_id, 'user_id' => $user_id, 'day' => date("Y-m-d"), 'createtime' => time()]);
		}
		//每日浏览圈子首页
		if ($user_id) {
			//经验奖励
			exps($circle_id, $user_id, 2);
		}
		//https://api.youdaike.com/static/index-header2/circle.png
        $users_agent = UsersService::getIndexCommunityWhereUsersLocated($user_id, $circle_id);
        $data['menu_lists'] = [
            ['label' => '圈子动态', 'value' => 1,'stated' => true,'icon' => '']
        ];
        //https://api.youdaike.com/static/index-header2/huzhu.png
        if($users_agent && isset($users_agent['users_identity']) && $users_agent['users_identity']){
            $data['menu_lists'][] = ['label' => '跑腿互助', 'value' => 2, 'stated' => true,'icon'=>''];
        }
		$this->success('请求成功', $data);
	}

	public function index_cate_click()
	{
        $user_id   = $this->auth->id;
        $circle_id = $this->request->post('circle_id', '');
        $cate_id   = $this->request->post('cate_id', 0);
        Indexcate::user_click_cate($user_id, $circle_id, $cate_id);
        $this->success('请求成功');
	}

    public function get_index_cate()
    {
        $user_id   = $this->auth->id;
        $circle_id = $this->request->post('circle_id', '');
        $res = Indexcate::get_index_cate_category($user_id, $circle_id);
        $this->success('请求成功', $res);
    }

    public function get_index_cate_content()
    {
        $circle_id = $this->request->post('circle_id', '');
        $cate_id   = $this->request->post('cate_id', 0);
        $res = Indexcate::get_index_cate_content($cate_id, $circle_id);
        $this->success('请求成功', $res);
    }
	//加入圈子
	private function join_circle($circle_id, $user_id)
	{
		$circle = Circle::get($circle_id);

		if (!$circle) {
			return true;
			//$this->success('圈子不存在',[],2);
		}

		$circle_user = CircleUser::where(['user_id' => $user_id, 'circle_id' => $circle_id])->find();

		if ($circle_user) {

			if ($circle_user->is_auth == 3) {
				return true;
			}

			return true;
		} else {
			return CircleUser::insert(['user_id' => $user_id, 'circle_id' => $circle_id, 'createtime' => time()]);
		}
	}

	/**
	 * 首页置顶动态
     * 
	 * @ApiMethod (POST)
	 * @param int $circle_id 圈子id
	 * @param int $cate_id  分类id
	 */
	public function top_trends()
	{
		$user_id   = $this->auth->id;
		$circle_id = $this->request->post('circle_id', '');
		$cate_id   = $this->request->post('cate_id', 0);//新增字段 分区ID

		if (!$circle_id) {
			$circle_id = Config::get("site2.ggqz");//公共圈子
		}

		$where              =   [];
		$where['is_draft']  =   2;      // 非草稿
		$where['state']     =   1;      // 状态正常
		$where['is_top']    =   1;      // 置顶的
		$where["is_see"]    =   1;      // 非私密
		
		$where['circle_id'] = $circle_id;
		
		if ($cate_id) {
			$where['cate_id'] = $cate_id;
		}

		$circles_id         = Config::get("site2.ggqz");
		$order = "id desc";

		$list = Trends::where($where)->order($order)->limit(10)->select();
		foreach ($list as $v) {
			$v->append(['userinfo']);
			$v->userinfo = getuser($v, $user_id, $circles_id);
		}
		$this->success("", $list);
	}

	/**
	 * 首页动态
     * 
	 * @ApiMethod (POST)
	 * @param int $circle_id 圈子id
	 * @param int $cate_id  分类id 
	 * @param int $page  当前页码
	 * @param int $count 每页数量
	 */
	public function trends()
	{
		$user_id   = $this->auth->id ? : 0;
		$circle_id = $this->request->post('circle_id', '');
		$cate_id   = $this->request->post('cate_id', 0);
		$day       = $this->request->post('day', 0);
		$page      = $this->request->post('page', 1);
		$count     = $this->request->post('count', 10);
		$where = [];
		$where['is_draft'] = 2;//不是草稿的
		$where['state'] = 1;//正常的
		$where['is_top'] = 2;//不置顶的

		if ($circle_id) {
			//$where['circle_id'] = $circle_id;
			//青聊社默认展示所有圈子数据 2024-10-15
			if($circle_id != 1) {
			    $where['circle_id'] = $circle_id;
			}
			if($user_id) {
				//获取圈友身份信息
				$circle_user = CircleUser::where(['user_id' => $user_id, 'circle_id' => $circle_id])->find();
				if($circle_user && $circle_user->identity <= 2) {
					//如果是管理员和群主，state=1 和 state=4
					$where['state'] = array('in', '1,4'); //正常的  审核中
				}
			}
		}

		if ($cate_id) {
			$where['cate_id'] = $cate_id;
		}

// 		$order          = "id desc";
// 		$wheretime      = "";

// 		if ($day == 1) {
// 			$wheretime = "today";
// 		} else if ($day == 2) {
// 			$wheretime = "yesterday";
// 		} else if ($day == 3) {
// 			$order = "vc_sum desc";
// 		}

		$list       = Trends::where(function($row) use ($where,$user_id){
                                        		    $row->where($where)->where(["user_id"=>$user_id,"is_see"=>2]);
                                        		})
		                                      ->whereOr(function($row) use ($where,$user_id){
		                                          $row->where($where)->where(["is_see" => 1]);
		                                      })
		                                      //->whereTime("create_time", $wheretime)
		                                      ->order("create_time desc,is_top asc")
		                                      ->paginate($count, false, ["page" => $page]);

		//$circles_id = Config::get("site2.ggqz");
        $scenicModel = new Scenic();
		foreach ($list as $k => $v) {
			$v->append(['userinfo','show','is_shop_goods']);
			$v->is_shop_goods = 0;
			$v->userinfo = getuser($v, $user_id, $circle_id);
			if($userinfo = getuser($v, $v->user_id, 1)){
		        if($userinfo['identity'] < 2){
	            	$v->is_shop_goods = 1;
	            }
			} 
			//仅自己可见
			if ($v->is_see == 2 && $v->user_id != $user_id) {
				$v->show = 'no';
			}else{
				$v->show = 'yes';
			}
			if(!strpos($v->goods_id, ',')) {
				$scenics = $scenicModel->where(['id'=>$v->goods_id])->find();
				//print_r($scenics);
				$v->scenic_imags = $scenics['scenic_images'];
				$v->scenic_address = $scenics['address'];
			}
		}
		$this->success("", $list);
	}


	public function trendsqq()
	{
		$user_id   = $this->auth->id ? : 0;
		$circle_id = $this->request->post('circle_id', '');
		$cate_id   = $this->request->post('cate_id', 0);
		$day       = $this->request->post('day', 0);
		$page      = (int)$this->request->post('page', 1);
		$count     = (int)$this->request->post('count', 10);
		$content_source = $this->request->post('_content_source', '1');
		$where = [];
		$where['is_draft']  = 2;//不是草稿的
// 		$where['state']     = 1;//正常的
		$where['is_top']    = 2;//不置顶的
		$circle_user        = [];
		$admin_users        = [];
		$order_by = "create_time desc,is_top asc";
        if($user_id){ // 获取用户所属当前圈子的信息
        	$circle_user = CircleUser::where(['user_id' => $user_id, 'circle_id' => $circle_id])->find();
        	$admin_users = CircleAdmin::where(['user_id' => $user_id, 'circle_id' => $circle_id])->find();
        }
        if ($cate_id) {
			$where['cate_id'] = $cate_id;
		}
        /*
            青聊社 -> $content_source = 8 AND $circle_id = 1
            社群   -> $content_source = 1 AND $circle_id = ?
        */
        $where_two = [];
        $query = Trends::where($where);
    
		if ( $content_source == 8 && $circle_id == 1 ) {
		    // 青聊社管理员，查看，所有未审核的动态，未设置推荐，已推荐的状态，所有圈子的动态；
		    // 排序规则 未审核-> 未设置推荐 -> 已推荐状态
	    	if(($circle_user || $admin_users) && ($circle_user->identity < 2 || ($admin_users && $admin_users->status == 2))) {
	    	    $where_two['state'] = ['in', '1,4']; //正常的  审核中
    	    	$where_two['is_t_recommend'] =  ['in', '1,2']; //未设置推荐，设置推荐的
    	    	$where_two['is_see'] =  1;  //公开的
	    		$query->where($where_two);
	    	    $order_by = "state desc,is_t_recommend desc,is_top asc,create_time desc";
	    	} else {
	    	    $where_two['state'] = 1; //正常的  审核中
    	        $where_two['is_t_recommend'] =  2; //，设置推荐的
    	        $where_two['is_see'] =  1; //公开的
	    		$query->where($where_two)
	    		->whereOr(function($row) use ($where, $circle_id){
            		$row->where(["circle_id" => $circle_id]);
        		});
	    	    $order_by = "is_t_recommend desc,is_top asc,create_time desc";
	    	}
		}
		elseif ( $content_source == 1 && $circle_id ){ // 社群
		    $where_two['circle_id'] = $circle_id;
            //社群管理员，查看，所有未审核及当前正常的圈子动态；
        	if(($circle_user || $admin_users) && ((isset($circle_user->identity) && $circle_user->identity < 2) || ($admin_users && $admin_users->status == 2))) {
        	     $where_two['state'] = ['in', '1,4']; //正常的  审核中
        	     $where_two['is_see'] =  1;  //公开的
    	    	 $query->where($where_two);
        	     $order_by = "state desc,create_time desc,is_top asc";
        	} else {
        	     $where_two['state'] = 1; //正常的  审核中
        	     $where_two['is_see'] =  1;  //公开的
                $query->where($where_two);
        	     $order_by = "create_time desc,is_top asc";
        	}
//    		$query->whereOr(function($row) use ($user_id){
//    	    	$row->where(["is_t_recommend"=>2]);
//    		});
        	$query->whereOr(function($row) use ($user_id){
    	    	$row->where(["user_id"=>$user_id,"is_see"=>2]);
    		});
		}
      	$list = $query->order($order_by)->paginate($count, false, ["page" => $page]);

		//$circles_id = Config::get("site2.ggqz");
        $scenicModel = new Scenic();
		foreach ($list as $k => $v) {
			$v->append(['userinfo', 'show', 'is_shop_goods']);
			$v->is_shop_goods = 0;
			$v->circle_name = Circle::where('id', $v->circle_id)->value('name');
			$v->userinfo = getuser($v, $user_id, $circle_id);
			if($userinfo = getuser($v, $v->user_id, 1)){
		        if($userinfo['identity'] < 2){
	            	$v->is_shop_goods = 1;
	            }
			} 
			//仅自己可见
			if ($v->is_see == 2 && $v->user_id != $user_id) {
				$v->show = 'no';
			}else{
				$v->show = 'yes';
			}
			if(!strpos($v->goods_id, ',')) {
				$scenics = $scenicModel->where(['id'=>$v->goods_id])->find();
				//print_r($scenics);
				$v->scenic_imags = $scenics['scenic_images'];
				$v->scenic_address = $scenics['address'];
			}
		}
		$this->success("", $list);
	}

	/**
	 * 发现页视频动态
     * 
	 * @ApiMethod (POST)
	 * @param int $circle_id 圈子id
	 * @param int $cate_id  分类id 
	 * @param int $page  当前页码
	 * @param int $count 每页数量
	 */
	public function video_trends()
	{
		$user_id   = $this->auth->id ? : 0;
		$circle_id = $this->request->post('circle_id', '');
		//$cate_id   = $this->request->post('cate_id', 0);
		//$day       = $this->request->post('day', 0);
		$page      = $this->request->post('page', 1);
		$count     = $this->request->post('count', 6);
		$where = [];
		$where['is_draft'] = 2;//不是草稿的
		$where['state'] = 1;//正常的
		$where['is_top'] = 2;//不置顶的
		$where['mp4_file'] = array("<>", ""); //mp4_file不为空

		if ($circle_id) {
			$where['circle_id'] = $circle_id;
			if($user_id) {
				//获取圈友身份信息
				$circle_user = CircleUser::where(['user_id' => $user_id, 'circle_id' => $circle_id])->find();
				if($circle_user && $circle_user->identity <= 2) {
					//如果是管理员和群主，state=1 和 state=4
					$where['state'] = array('in', '1,4'); //正常的  审核中
				}
			}
		}
		//if ($cate_id) { $where['cate_id'] = $cate_id;}
		$list = Trends::where(function($row) use ($where,$user_id){
                                $row->where($where)->where(["user_id"=>$user_id,"is_see"=>2]);
                            })
		                    ->whereOr(function($row) use ($where,$user_id){
		                      	$row->where($where)->where(["is_see" => 1]);
		                    })
		                    ->order("is_top asc,create_time desc")
		                    ->paginate($count, false, ["page" => $page]);
		$circles_id = Config::get("site2.ggqz");
		foreach ($list as $k => $v) {
			$v->append(['userinfo','show']);
			$v->userinfo = getuser($v, $user_id, $circles_id);
			//仅自己可见
			if ($v->is_see == 2 && $v->user_id != $user_id) {
				$v->show = 'no';
			}else{
				$v->show = 'yes';
			}
        	$scenicModel = new Scenic();
			if($v->goods_id != null && !strpos($v->goods_id, ',')) {
				$scenics = $scenicModel->where(['id'=>$v->goods_id])->find();
				$v->scenic_imags = $scenics['scenic_images'];
				$v->scenic_address = $scenics['address'];
				$v->total_sales = $scenics['total_sales'];
    			if($v->total_sales == null || $v->total_sales == 0) {
    			    $v->total_sales = mt_rand(300,500);
    			}
			}
			if(strpos($v->goods_id, ',')) {
			    $v->total_sales = mt_rand(300,500);
			}
		}
		$this->success("", $list);
	}

	/**
	 * 关注人的动态
     * 
	 * @ApiMethod (POST)
	 * @param int $page  当前页码
	 * @param int $count 每页数量
	 */
	public function followee_trends()
	{
		$user_id = $this->auth->id ? : 0;
		$page      = $this->request->post('page', 1);
		$count     = $this->request->post('count', 10);
       
		$where = [];
		$where['is_draft'] = 2;//不是草稿的
		$where['state'] = 1;//正常的
		//根据当前登录用户信息获取关注人的id
		$where2 = [];
		$where2["user_id"] = $this->auth->id;
		$tmp_followees = '1';
		$list_tmp = Follow::where($where2)->select();
		if(count($list_tmp)) {
			foreach ($list_tmp as $k => $v) {
				$tmp_followees = $tmp_followees . ','. $v->user2_id;
			}
		}
		$where['user_id'] = array('in', $tmp_followees); //关注人的id

		$list = Trends::where(function($row) use ($where,$user_id){
                    $row->where($where)->where(["user_id"=>$user_id,"is_see"=>1]);
                })
		        ->whereOr(function($row) use ($where,$user_id){
		            $row->where($where)->where(["is_see" => 1]);
		        })
		        ->order("create_time desc")
		        ->paginate($count, false, ["page" => $page]);

		$circles_id = Config::get("site2.ggqz");
		$scenicModel = new Scenic();
		foreach ($list as $k => $v) {
			$v->append(['userinfo','show']);
			$v->userinfo = getuser($v, $user_id, $circles_id);
			if ($v->is_see == 2 && $v->user_id != $user_id) {
				$v->show = 'no';
			}else{
				$v->show = 'yes';
			}
			if(!strpos($v->goods_id, ',')) {
				$scenics = $scenicModel->where(['id'=>$v->goods_id])->find();
				//print_r($scenics);
				$v->scenic_imags = $scenics['scenic_images'];
				$v->scenic_address = $scenics['address'];
			}
		}

		$this->success("", $list);
	}

	/**
	 * 搜索记录,猜你想搜
	 */
	public function soulog()
	{
		$user_id       = $this->auth->id;
		$site          = Config::get('site2');
		$list          = Soulog::where(['user_id' => $user_id])->order('id desc')->limit(10)->select();
		$data['list']  = $list ? $list : [];
		$data['list2'] = $site['sou'];

		$this->success("", $data);
	}

	/**
	 * 删除搜索记录
     * 
	 * @ApiMethod (POST)
	 * @param int $soulog_id  搜索记录id
	 */
	public function soulog_del()
	{
		$user_id = $this->auth->id;
		$sou_id  = $this->request->post('soulog_id', 0);

		$soulog = Soulog::where(['user_id' => $user_id, 'id' => $sou_id])->find();
		if (!$soulog) {
			$this->success("数据不存在", [], 2);
		}
		$res = Soulog::where(['user_id' => $user_id, 'id' => $sou_id])->delete();

		if ($res) {
			$this->success("成功", []);
		} else {
			$this->error('出差了');
		}
	}

	/**
	 * 开始搜索
     * 
	 * @ApiMethod (POST)
	 * @param int $title  搜索内容，必填
	 * @param int $type   搜索类型 （1 圈友动态，2 动态，3 圈友，4 话题，5 集市）
	 */
	public function soucontent()
	{
		$user_id = $this->auth->id;
		$user_id=76;
		$title      = $this->request->post('title', '');
		$type       = $this->request->post('type', 1);
		$circles_id = Config::get("site2.ggqz");//公共圈子

		if (!$title) {
			$this->success("请输入搜索内容", [], 2);
		}

		if ($type == 1) {
			//圈友
			$haoyou = \app\common\model\User::where(['nickname' => ['like', "%$title%"]])->limit(10)->select();
			//动态
			$where          = [];
			$where['title'] = ['like', "%$title%"];
			//$list         = Trends::where($where)->order('vc_sum desc')->limit(10)->select();
			$list           = Trends::where($where)->limit(10)->select();
			
			foreach ($list as $v) {
				$v->append(['userinfo']);
				$v->userinfo = getuser($v, $user_id, $circles_id);
			}
			$data['haoyou'] = $haoyou;
			$data['list']   = $list;

		} else if ($type == 2) {//动态
			//动态
			$where          = [];
			$where['title'] = ['like', "%$title%"];
			//$list         = Trends::where($where)->order('vc_sum desc')->limit(30)->select();
			$list           = Trends::where($where)->limit(30)->select();
			foreach ($list as $v) {
				$v->append(['userinfo']);
				$v->userinfo = getuser($v, $user_id, $circles_id);
			}
			$data['list'] = $list;
		} else if ($type == 3) {//圈友
			$haoyou = \app\common\model\User::where(['nickname' => ['like', "%$title%"]])->limit(30)->select();
			foreach ($haoyou as $v) {
				$v->visible(['id', 'number', 'nickname', 'avatar', 'fans']);
				$v->append(['is_follow']);
				//$v->is_follow = Db::connect($this->connection)->name("publics_follow")->where(['user2_id' => $v->id, 'user_id' => $this->auth->id])->find() ? 1 : 2;
				$v->is_follow = Follow::where(['user2_id' => $v->id, 'user_id' => $this->auth->id])->find() ? 1 : 2;
			}
			$data['haoyou'] = $haoyou;
		} else if ($type == 4) {//话题
			$huati = Huati::where(['title' => ['like', "%$title%"]])->limit(30)->select();
			foreach ($huati as $v) {
				$v->append(['view', 'comment']);
				$v->view    = Huati::where(['huati_id' => $v->id])->sum('view');
				$v->comment = Huati::where(['huati_id' => $v->id])->sum('comment');
			}
			$data['huati'] = $huati;
		} else if ($type == 5) {//集市
			$haoyou        = Goods::where(['title' => ['like', "%$title%"]])->limit(30)->select();
			$data['goods'] = $haoyou;
		}

		$sou = Soulog::where(['user_id' => $user_id, 'words' => $title])->find();
		if ($sou) {
			$sou->save(['words' => $title, 'createtime' => time()]);
		} else {
			Soulog::create(['user_id' => $user_id, 'words' => $title, 'createtime' => time()]);
		}

		$this->success("返回", $data);
	}

	/**
	 * 等级列
     * 
	 * @ApiMethod (POST)
	 * @param int $user_id   用户id，必填
	 * @param int $circle_id   圈子id，必填
	 */
	public function level_list()
	{
		$user_id   = $this->request->post('user_id', 0);
		$circle_id = $this->request->post('circle_id', 0);
		$circle = CircleUser::where(['user_id' => $user_id, 'circle_id' => $circle_id, 'identity' => ['in', '1,2,3']])->find();
		if (!$circle) {
			$this->success("圈友不存在", [], 2);
		}
		$circle->append(['userinfo']);
		$circle->userinfo = $circle->getuser($circle, $user_id);

		$data['user'] = $circle;//用户等级信息

		$list = CircleLevel::with(['publiclevel'])
		                   ->where(['circle_id' => $circle_id])
		                   ->order('level asc')
		                   ->select();
		foreach ($list as $row) {
			$row->visible(['id', 'circle_id', 'nickname', 'level', 'createtime']);
			$row->visible(['publiclevel']);
			$row->getRelation('publiclevel')->visible(['name', 'score', 'bg_color', 'font_color']);
		}
		$data['level'] = $list;//级别列表
		$arr = [
			['id' => 1, 'name' => '加入圈子'],
			['id' => 2, 'name' => '每日活跃'],
			['id' => 3, 'name' => '发布动态'],
			['id' => 4, 'name' => '圈内互动'],
			['id' => 5, 'name' => '举报'],
		];
		foreach ($arr as $k => $v) {
			$arr[$k]['list'] = PublicsExp::where(['type' => $v['id']])->order('id asc')->select();
		}
		$data['exp'] = $arr;//经验说明
		$this->success("返回", $data);
	}

	/**
	 * 配置信息
	 */
	public function config()
	{
		$site = Config::get("site2");
		$data['report']        = site($site['report']);
		$data['report2']       = site($site['report2']);
		$data['report3']       = site($site['report3']);
		$data['report4']       = site($site['report4']);
		$data['shop_type']     = site($site['shop_type']);
		$data['tan']           = $site['tan'];    //弹窗
		$data['shiyong']       = $site['shiyong'];//使用指南
		$data['hudong']        = $site['hudong']; //发布规则
		$data['fabu']          = $site['fabu'];   //举报消息规范
		$data['ht_image']      = cdnurl($site['ht_image'], true);
		$data['warn']          = $site['warn'];         //二手集市警告
		$data['liyou']         = $site['liyou'];        //加入圈子申请理由简介
		$data['topic']         = $site['topic'];        //加入圈子答题认证简介
		$data['trends_detail'] = $site['trends_detail'];//动态分类说明
		$data['ban_day']       = $site['ban_day'];      //封禁时间
		$data['hmdsm']         = $site['hmdsm'];        //黑名单说明
		$data['jbgf']          = $site['jbgf'];         //举报规范
		$data['dtyz']          = $site['dtyz'];         //为什么答题验证？
		$data['dtgz']          = $site['dtgz'];         //答题规则
		$data['second']        = $site['second'];       //答题倒计时
		$data['yhxy']          = $site['yhxy'];         //用户协议
		$data['yszc']          = $site['yszc'];         //隐私政策
		$data['fxts']          = $site['fxts'];         //风险提示
		$data['ggqz']          = $site['ggqz'];         //公共圈子ID

		$this->success("", $data);
	}

	/**
	 * 获取圈子信息
     * 
	 * @ApiMethod (POST)
	 * @param int $circle_id   圈子id，必填
	 */
	public function get_circle()
	{
		$user_id   = $this->auth->id;
		$circle_id = $this->request->post('circle_id', '');
		$circle = Circle::get($circle_id);
		if (!$circle) {
			$this->success('圈子信息不存在', [], 2);
		}
		//加入方式
		$circle->admin_num = CircleAdmin::where(['type' => 1, 'circle_id' => $circle_id, 'status' => 1])->count();
		$this->success('成功', $circle);
	}

	/**
	 * 转发
     * 
	 * @ApiMethod (POST)
	 * @param int $type   类型，必填（1 动态，2 商品）
	 * @param int $id     动态或商品id，必填
	 */
	public function forward()
	{
		$user_id = $this->auth->id;
		$type    = $this->request->post('type');
		$id      = $this->request->post('id', 0);

		if ($type == 1) {
			$detail = Trends::get($id);
		} else if ($type == 2) {
			$detail = Goods::get($id);
		} else {
			$this->success('参数错误', [], 2);
		}

		if (!$detail) {
			$this->success('信息不存在', [], 2);
		}
		$detail->setInc('forward', 1);
		$this->success('成功');
	}

	/**
	 * 生成海报图片
	 * 
	 * @param int $type   类型，必填（1 动态，2 商品）
	 * @param int $id     动态或商品id，必填
	 */
	public function get_poster()
	{
		$type = $this->request->param('type', 0);
		$id   = $this->request->param('id', 0);
		if ($type == 1) {
			$detail = Trends::get($id);
			$image  = $detail->images ? explode(',', $detail->images) : '';
		} else if ($type == 2) {
			$detail = Goods::get($id);
			$image  = $detail->images ? explode(',', $detail->images) : '';
		} else {
			$this->success('参数错误', [], 2);
		}
		$invitcode = $this->invitcode($type,$id);
		//	初始化类库
		vendor("SimpleImage");
		$SimpleImage = new SimpleImage();
		//	设置海报背景preg_replace('/s/','',$detail->title)
		$SimpleImage->setBackground(cdnurl('/poster/bak.png', true));
		//	标题
		$SimpleImage->setText(mb_substr($detail->title, 0, 16, "UTF-8"), 23, 50, null, 26, "21,20,20", 0);
		//	内容
		$content = preg_replace('/\s+/', '', $detail->detail);
		//$SimpleImage->setText($detail->detail,30,90,null,20,"21,20,20",0);
		$SimpleImage->setText(mb_substr($content, 0, 20, "UTF-8"), 25, 100, null, 20, "21,20,20", 0);
		//图片海报
		if ($image) {
			$SimpleImage->setText(mb_substr($content, 20, 20, "UTF-8") ? mb_substr($content, 60, 18, "UTF-8") . '...' : '', 25, 140, null, 20, "21,20,20", 0);
			$left = 15;
			foreach ($image as $item) {
				$SimpleImage->setImage(cdnurl($item, true), $left, 149, 180, 180, 90);
				$left += 200;
			}
			//	用户Logo
			$SimpleImage->setFilletImage($detail->avatar, 60, 360, 80, 80, 100);
			//	用户昵称
			$SimpleImage->setText($detail->nickname, 160, 420, null, 30, "21,20,20", 0);
			//	二维码
			$SimpleImage->setImage($invitcode, 462, 520, 120, 120, 90);
		} else {
			$SimpleImage->setText(mb_substr($content, 20, 20, "UTF-8"), 25, 140, null, 20, "21,20,20", 0);
			$SimpleImage->setText(mb_substr($content, 40, 20, "UTF-8"), 25, 180, null, 20, "21,20,20", 0);
			$SimpleImage->setText(mb_substr($content, 60, 18, "UTF-8") ? mb_substr($content, 60, 18, "UTF-8") . '...' : '', 25, 220, null, 20, "21,20,20", 0);
			// 二维码海报
			$SimpleImage->setImage($invitcode, 462, 520, 120, 120, 90);
			//	用户Logo
			$SimpleImage->setFilletImage($detail->avatar, 60, 810, 80, 80, 100);
			//	用户昵称
			$SimpleImage->setText($detail->nickname, 160, 870, null, 30, "21,20,20", 0);
		}

		//生成二维码
		$day = date("Y-m-d");
		$dir = iconv("UTF-8", "GBK", $day);
		$dir = "poster/" . $dir;
		if (!file_exists($dir)) {
			mkdir($dir, 0777);
		}
		//$dir = $dir.'/'.date("YmdHis") . rand(100000, 999999).'.png';
		$dir = $dir . '/' . date("YmdHis") . '.png';

		$SimpleImage->save($dir);
		//add_oss($dir);//同步到OSS
		//$this->success('成功', ['poster' => cdnurl('/' . $dir, true)]);
		$url_img = 'http://api.youdaike.com/' . $dir;
		$this->success('成功', ['poster' => $url_img]);
	}

	//生成二维码
	private function invitcode($type,$id)
	{
		$user_id = $this->auth->id;
		/*$config  = get_addon_config('third');
		$APPID     = $config['wechatMini']['app_id'];
		$APPSECRET = $config['wechatMini']['app_secret'];*/
		$config = Service::getConfig('wechat');
		$APPID = $config['miniapp_id'];
		$APPSECRET = $config['miniapp_secret'];
		//获取access_token
		$access_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$APPID&secret=$APPSECRET";
		//缓存access_token
		if (Cache('access_token')) {
			$ACCESS_TOKEN = Cache('access_token');
		} else {
			$json = $this->httpRequest($access_token);
			$json = json_decode($json, true);
			Cache('access_token', $json['access_token'], 3000);
			$ACCESS_TOKEN = $json["access_token"];
		}
		//构建请求二维码参数
		//path是扫描二维码跳转的小程序路径，可以带参数?id=xxx
		//width是二维码宽度

		if($type == 1){
			$path = "/pagesA/index/dynamicDetails?id=".$id;
		}else{
			$path = "/pagesA/market/details?goodsId=".$id;
		}

		//$qcode ="https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=$ACCESS_TOKEN";//方的
		$qcode = "https://api.weixin.qq.com/wxa/getwxacode?access_token=$ACCESS_TOKEN";//圆的
		$param = json_encode(["path" => $path, "width" => 150]);

		//POST参数
		$result = $this->httpRequest($qcode, $param, "POST");
		//生成二维码
		$day = date("Y-m-d");
		$dir = iconv("UTF-8", "GBK", $day);
		$dir = "invitcode/" . $dir;
		if (!file_exists($dir)) {
			mkdir($dir, 0777);
		}

		$filename = $dir . '/' . $user_id . '.png';
		file_put_contents($filename, $result);
		$base64_image = "data:image/jpeg;base64," . base64_encode($result);

		//add_oss($filename);//同步到OSS
		return $filename;
	}

	//把请求发送到微信服务器换取二维码
	private function httpRequest($url, $data = '', $method = 'GET')
	{
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
		curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
		if ($method == 'POST') {
			curl_setopt($curl, CURLOPT_POST, 1);
			if ($data != '') {
				curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
			}
		}

		curl_setopt($curl, CURLOPT_TIMEOUT, 30);
		curl_setopt($curl, CURLOPT_HEADER, 0);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		$result = curl_exec($curl);
		curl_close($curl);

		return $result;
	}

	/**
	 * 发送消息
	 */
	public function send()
	{
		//halt(link_url());
		$list = Rult::select();
		foreach ($list as $k => $v) {
			$arr = [];
			//获取相隔分钟
			$min = floor((time() - $v->send_time) / 60);
			if ($min >= $v->send_min) {
				$page = $v->send_num + 1;
				//筛选动态信息
				$list2 = Trends::where(['circle_id' => $v->circle_id, 'cate_id' => ["in", $v->cate_ids]])
				                                 ->order('create_time asc')
				                                 ->paginate($v->send_num, false, ["page" => $page]);
				if (count($list2) > 0) {
					foreach ($list2 as $k2 => $v2) {
						$arr[] = ['title' => $v2->title, 'url' => link_url($v2->id)];
					}
					//请求第三方接口发送消息
					//发送成功后记录发送时间
					$v->save(['page' => $page, 'send_time' => time()]);
				}
			}
		}
	}

	/**
	 * 轮播定时下架
	 */
	public function MinBanner()
	{
		$list = Banner::where(['status' => 2, 'end_time' => ['gt', 0]])->select();
		foreach ($list as $k => $v) {
			if (time() > $v->end_time) {
				$v->save(['status' => 4]);
			}
		}
		$list2 = Banner2::where(['status' => 2, 'end_time' => ['gt', 0]])->select();
		foreach ($list2 as $k2 => $v2) {
			if (time() > $v2->end_time) {
				$v2->save(['status' => 4]);
			}
		}
	}

	private function doJob($data)
	{
		//	开启事务
		Db::startTrans();
		//	监听
		try {
			$rult = Rult::where(['id' => $data['rult_id']])->find();
			if ($rult) {
				$page = $rult->send_num + 1;
				//筛选动态信息
				$list = Trends::where(['circle_id' => $rult->circle_id, 'cate_id' => ["in", $rult->cate_ids]])
				                                ->order('create_time asc')
				                                ->paginate($rult->send_num, false, ["page" => $page]);
				$send = [];
				$arr  = [];
				if (count($list) > 0) {
					foreach ($list as $k => $v) {
						$arr[] = ['title' => $v->title, 'url' => link_url($v->id)];
					}
					//获取圈子外链名称 网址 内容
					$circle = Circle::get($rult->circle_id);
					if ($circle) {
						$arr[] = ['title' => $circle->url_name, 'url' => $circle->url_web, 'url' => $circle->content];
						//请求第三方接口发送消息
						$send['wxcode'] = $rult->wxcode;//微信号
						$send['crowd']  = $rult->crowd; //群聊名称
						$send['list']   = $arr;         //信息列表
						//第三方接口发送
						//发送成功后记录发送时间
						$rult->save(['page' => $page, 'send_time' => time()]);
						//定时任务
						queue_delay($rult->send_min * 60, ["rult_id" => $rult->id]);
					} else {
						//发送成功后记录发送时间
						$rult->save(['page' => 0, 'send_time' => time()]);
						//定时任务
						queue_delay($rult->send_min * 60, ["rult_id" => $rult->id]);
					}
				}
			}
			//	提交事务
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			Log::error($data);
			Log::error($e->getMessage());
		}
		return true;
	}

	/**
	 * 圈子信息
     * 
	 * @ApiMethod (POST)
	 * @param int $circle_id   圈子id，必填
	 */
	public function circle_detail()
	{
		$circle_id = $this->request->post('circle_id', 0);
		$circle = Circle::where(['id' => $circle_id])->find();
		if ($circle) {
			$this->success('成功', ['url_name' => $circle['url_name'], 'url_web' => $circle['url_web'], 'url_content' => $circle['url_content']]);
		} else {
			$this->success('失败', [], 2);
		}
	}

	public function test()
	{
		var_dump(link_url(628));
	}

	public function del_dt(){
		$list = Follow::select();
		foreach ($list as $v){
			$user = Db::name("user")->where(['id'=>$v->user2_id])->find();
			if(!$user){
				$v->delete();
			}
		}
		$this->success('成功', []);
	}

    /**
     * 根据圈子id获取圈子分享的二维码
     * @Author   Ming
     * @ApiMethod (POST)
	 * @param int $isWeiXin   类型（1 微信，2 H5）
	 * @param int $circleId   圈子id，必填
     */
    public function shareCircle()
    {
        $isWechat = $this->request->post("isWeiXin");
        $circleId = $this->request->post("circleId");
        //微信二维码
        /*if ($isWechat == 1) {
            $code = $this->generateCode($circleId);
        }else{
            $url    = 'http://'.$_SERVER['HTTP_HOST'].'/pages/index/dynamicDetails?id=816';
        }*/
        $code = $this->generateCode($circleId);
        $data =['code' => $code];
       	$this->success('成功', $data);
    }

    //生成二维码
    private function generateCode($circleId)
	{
		/*$config    = get_addon_config('third');
		$APPID     = $config['wechatMini']['app_id'];
		$APPSECRET = $config['wechatMini']['app_secret'];*/
		$config = Service::getConfig('wechat');
		$APPID = $config['miniapp_id'];
		$APPSECRET = $config['miniapp_secret'];
		//获取access_token
		$access_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$APPID&secret=$APPSECRET";
		//缓存access_token
		if (Cache('access_token')) {
			$ACCESS_TOKEN = Cache('access_token');
		} else {
			$json = $this->httpRequest($access_token);
			$json = json_decode($json, true);
			Cache('access_token', $json['access_token'], 3000);
			$ACCESS_TOKEN = $json["access_token"];
		}
		//构建请求二维码参数
		//path是扫描二维码跳转的小程序路径，可以带参数?id=xxx
		//width是二维码宽度
		//$path = "/pages/index/index?id=".$circleId;//青聊社的地址
		$path = "/pagesC/video/index?circleId=".$circleId."&source=1"; //整合后的地址
		//$qcode ="https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=$ACCESS_TOKEN";//方的
		$qcode = "https://api.weixin.qq.com/wxa/getwxacode?access_token=$ACCESS_TOKEN";//圆的，小程序中暂时使用圆的
		$param = json_encode(["path" => $path, "width" => 380]);

		//POST参数
		$result = $this->httpRequest($qcode, $param, "POST");
		$base64_image = "data:image/jpeg;base64," . base64_encode($result);
		//add_oss($filename);//同步到OSS
		return $base64_image;
	}

	/**
	 * 微信小程序获取手机号码，并更新手机号
     * @Author   Ming
     * @ApiMethod (POST)
	 * @param int $code  小程序code
	 */
	public function getPhoneNumber() {
		$code      = $this->request->post("code");
		/*$config    = get_addon_config('third');
		$APPID     = $config['wechatMini']['app_id'];
		$APPSECRET = $config['wechatMini']['app_secret'];*/
		$config = Service::getConfig('wechat');
		$APPID = $config['miniapp_id'];
		$APPSECRET = $config['miniapp_secret'];
		//获取access_token
		$access_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$APPID&secret=$APPSECRET";
		//缓存access_token
		if (Cache('access_token')) {
			$ACCESS_TOKEN = Cache('access_token');
		} else {
			$json = $this->httpRequest($access_token);
			$json = json_decode($json, true);
			Cache('access_token', $json['access_token'], 3000);
			$ACCESS_TOKEN = $json["access_token"];
		}
		//获取手机号
		$userPhoneNumberUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=$ACCESS_TOKEN";
		$param = json_encode(["code" => $code]);//
		//POST参数
		$result = $this->httpRequest($userPhoneNumberUrl, $param, "POST");
		$data = json_decode($result, TRUE);
		return $this->success('成功', $data);
		//return $this->success('成功', $data);
	}

    /**
     * 根据用户id获取用户分享的二维码
     * @Author   Ming
     * @ApiMethod (POST)
	 * @param int $userId   用户id，必填
     */
    public function shareUser()
    {
        $userId = $this->request->post("userId");
        if (!$userId) {
			$this->error("用户ID不能为空");
		}
		/*$config    = get_addon_config('third');
		$APPID     = $config['wechatMini']['app_id'];
		$APPSECRET = $config['wechatMini']['app_secret'];*/
		$config = Service::getConfig('wechat');
		$APPID = $config['miniapp_id'];
		$APPSECRET = $config['miniapp_secret'];
		//获取access_token
		$access_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$APPID&secret=$APPSECRET";
		//缓存access_token
		if (Cache('access_token')) {
			$ACCESS_TOKEN = Cache('access_token');
		} else {
			$json = $this->httpRequest($access_token);
			$json = json_decode($json, true);
			Cache('access_token', $json['access_token'], 3000);
			$ACCESS_TOKEN = $json["access_token"];
		}
		//构建请求二维码参数
		//path是扫描二维码跳转的小程序路径，可以带参数?id=xxx
		//width是二维码宽度
		$path = "/pagesA/mine/mineOther?share=1&userId=".$userId;
		//$qcode ="https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=$ACCESS_TOKEN";//方的
		$qcode = "https://api.weixin.qq.com/wxa/getwxacode?access_token=$ACCESS_TOKEN";//圆的，小程序中暂时使用圆的
		$param = json_encode(["path" => $path, "width" => 380]);
		//POST参数
		$result = $this->httpRequest($qcode, $param, "POST");
		$base64_image = "data:image/jpeg;base64," . base64_encode($result);
        $data =['code' => $base64_image];
       	$this->success('成功', $data);
    }
    
    /**
     * 获取客服信息
     * @Author   Ming
     */
    public function customerService()
    {
		$serviceModel = new CustomerService();
		$list = $serviceModel->order("id asc")->select();
		$this->success('客服信息', $list);
    }
    
	/**
	 * 加群文案信息
     * 
	 * @ApiMethod (POST)
	 * @param int $circle_id 圈子id
	 */
	public function groupInfo()
	{
		$circle_id = $this->request->post('circle_id', 0);
		if (!$circle_id) {
			$this->success('参数错误', [], 2);
		}

		$where              = [];
		$where['circle_id'] = $circle_id;
		$where['is_show']   = 1;
		$where['status']    = 2;
		$group = array();
		$group = \app\common\model\trends\Group::where($where)->find();
		$this->success("加群文案信息", $group);
	}
}
